package com.ruoyi.framework.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.BaseDateEntity;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.BasicsEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Lion Li
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject)) {
                if (metaObject.getOriginalObject() instanceof BaseEntity) {
                    BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                    Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
                        ? baseEntity.getCreateTime() : new Date();
                    baseEntity.setCreateTime(current);
                    baseEntity.setUpdateTime(current);
                    String username = StringUtils.isNotBlank(baseEntity.getCreateBy())
                        ? baseEntity.getCreateBy() : getLoginUsername();
                    // 当前已登录 且 创建人为空 则填充
                    baseEntity.setCreateBy(username);
                    // 当前已登录 且 更新人为空 则填充
                    baseEntity.setUpdateBy(username);
                } else if (metaObject.getOriginalObject() instanceof BasicsEntity) {
                    BasicsEntity basicsEntity = (BasicsEntity) metaObject.getOriginalObject();
                    Date current = ObjectUtil.isNotNull(basicsEntity.getCreateTime())
                        ? basicsEntity.getCreateTime() : new Date();
                    basicsEntity.setCreateTime(current);
                    basicsEntity.setUpdateTime(current);
                    Long userId = ObjectUtil.isNotEmpty(basicsEntity.getCreateId())
                        ? basicsEntity.getCreateId() : LoginHelper.getUserId();
                    // 当前已登录 且 创建人为空 则填充
                    basicsEntity.setCreateId(userId);
                    // 当前已登录 且 更新人为空 则填充
                    basicsEntity.setUpdateId(userId);
                } else if (metaObject.getOriginalObject() instanceof BaseDateEntity){
                    BaseDateEntity baseDateEntity = (BaseDateEntity) metaObject.getOriginalObject();
                    Date current = ObjectUtil.isNotNull(baseDateEntity.getCreateTime())
                        ? baseDateEntity.getCreateTime() : new Date();
                    baseDateEntity.setCreateTime(current);
                    baseDateEntity.setUpdateTime(current);
                }
                else {
                    Date current = new Date();
                    this.setFieldValByName("createTime", current, metaObject);
                    this.setFieldValByName("updateTime", current, metaObject);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject)) {
                if (metaObject.getOriginalObject() instanceof BaseEntity) {
                    BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                    Date current = new Date();
                    // 更新时间填充(不管为不为空)
                    baseEntity.setUpdateTime(current);
                    String username = getLoginUsername();
                    // 当前已登录 更新人填充(不管为不为空)
                    if (StringUtils.isNotBlank(username)) {
                        baseEntity.setUpdateBy(username);
                    }
                } else if (metaObject.getOriginalObject() instanceof BasicsEntity) {
                    BasicsEntity basicsEntity = (BasicsEntity) metaObject.getOriginalObject();
                    Date current = new Date();
                    // 更新时间填充(不管为不为空)
                    basicsEntity.setUpdateTime(current);
                    Long userId = LoginHelper.getUserId();
                    // 当前已登录 更新人填充(不管为不为空)
                    if (ObjectUtil.isNotEmpty(userId)) {
                        basicsEntity.setUpdateId(userId);
                    }
                }else if (metaObject.getOriginalObject() instanceof BaseDateEntity) {
                    BaseDateEntity baseDateEntity = (BaseDateEntity) metaObject.getOriginalObject();
                    Date current = new Date();
                    // 更新时间填充(不管为不为空)
                    baseDateEntity.setUpdateTime(current);
                }
                else {
                    this.setFieldValByName("updateTime", new Date(), metaObject);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUsername();
    }

}
